mod models;

use std::time::Duration;

use sea_orm::*;

use models::{prelude::*, todo};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenvy::dotenv().ok();

    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set in .env");

    let mut opt = ConnectOptions::new(database_url);
    opt.max_connections(2)
        .connect_timeout(Duration::from_secs(8))
        .acquire_timeout(Duration::from_secs(8))
        .idle_timeout(Duration::from_secs(8))
        .max_lifetime(Duration::from_secs(8))
        .sqlx_logging(true);
    let db = Database::connect(opt).await?;

    // Insert
    let insert_todo = todo::ActiveModel {
        title: Set("hello".to_owned()),
        status: Set(todo::Status::Active),
        created_at: Set(chrono::Local::now().naive_local()),
        ..Default::default()
    };
    let todo = insert_todo.insert(&db).await?;
    println!("insert todo {:#?}", todo);

    // Update
    let mut model: todo::ActiveModel = todo.into();
    model.status = Set(todo::Status::Finished);
    model.updated_at = Set(Some(chrono::Local::now().naive_local()));
    let todo = model.update(&db).await?;
    println!("update todo {:#?}", todo);

    // Select
    let todos = Todo::find().all(&db).await?;
    for todo in todos {
        println!("select todo {:#?}", todo);
    }

    // Delete
    // Todo::delete_by_id(todo.id).exec(&db).await?;

    Ok(())
}
